package com.central.apps.handler.purchase;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.controller.FlowCommonController;
import com.central.app.service.HandlerService;
import com.central.apps.util.StringUtil;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.SysUserUtil;
import com.central.common.web.PageResult;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

//采购验收
@Slf4j
@Component
public class PuracceptHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;

    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        System.out.println("===> enter PuracceptHandler beforDelete");
        System.out.println("===> app:" + app);
        System.out.println("===> objName:" + objName);
        System.out.println("===> id:" + id);
        System.out.println("===> isLogic:" + isLogic);
        if ("gq_puraccept".equals(objName)) {
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puraccept where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)) {
                Map<String, Object> map = bySql.get(0);
                String accertificate = MapUtils.getString(map, "accertificate");
                String receiptnum = MapUtils.getString(map, "receiptnum");
                handlerService.updateBySql("update gq_purchasereceipt set accertificate =0 where receiptnum='" + receiptnum + "'");
                String status = "新建";
                handlerService.updateBySql("update gq_purchasereceipt set status ='" + status + "' where receiptnum='" + receiptnum + "'");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_purchasereceipt where receiptnum='" + receiptnum + "'");
                String id1 = MapUtils.getString(bySql1.get(0), "id");
                handlerService.updateBySql("update gq_prtdetailline set accertificate=0 where prtid='" + id1 + "'");
            }
        } else if ("gq_puracceptline".equals(objName)) {
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puracceptline where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)) {
                for (int i = 0; i < bySql.size(); i++) {
                    Map<String, Object> map = bySql.get(i);
                    String prtsummarylineid = MapUtils.getString(map, "prtsummarylineid");
                    handlerService.updateBySql("update gq_prtdetailline set accertificate=0 where id='" + prtsummarylineid + "'");
                }
            }
        }
        super.beforDelete(app, objName, id, isLogic);
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        System.out.println("===> enter PuracceptHandler afterExcuteFlow");
        System.out.println("===> app:" + app);
        System.out.println("===> id:" + id);
        System.out.println("===> flowNode:" + flowNode);
        System.out.println("===> op:" + op);
        System.out.println("===> event:" + event);
        if (flowNode.getId().equals("complete") && op.isFlag()) {
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_puraccept where id=" + id);
            //将填写信息同步到子表中
            LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
            String username = loginAppUser.getUsername();
            //int usercode = loginAppUser.getField10();//获取当前登录人
            //handlerService.updateBySql("update gq_testinforma  set aptecindica='"+list.get(0).get("aptecindica")+"',receiveqty="+list.get(0).get("receiveqty")+",testresult='"+list.get(0).get("testresult")+"' where username= '"+username+"' and puracceptlineid="+id);

            //查询审批子表，如果都不为空，说明会签完了，执行下一步结果
            boolean isres = true;
            for (Map<String, Object> stringObjectMap : list) {
                List<Map<String, Object>> islists = handlerService.findBySql("select id, accertificate from gq_puracceptline where accertificate ='" + stringObjectMap.get("accertificate") + "'");
                for (Map<String, Object> islist : islists) {
                    List<Map<String, Object>> islistaa = handlerService.findBySql("select id from gq_testinforma where (testresult is null or testresult='' ) and puracceptlineid=" + islist.get("id"));
                    if (CollectionUtils.isNotEmpty(islistaa)) {
                        isres = false;
                        break;
                    }
                }

            }
            if (isres) {
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puraccept where id=" + id);
                Map<String, Object> map = bySql.get(0);
                String accertificate = MapUtils.getString(map, "accertificate");
                String receiptnum = MapUtils.getString(map, "receiptnum");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_puracceptline where accertificate ='" + accertificate + "'");
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    for (int i = 0; i < bySql1.size(); i++) {
                        Map<String, Object> map1 = bySql1.get(i);
                        Float qualquantity = MapUtils.getFloat(map1, "qualquantity");
                        Float receiveqty = MapUtils.getFloat(map1, "receiveqty");//合格
                        String insresults = MapUtils.getString(map1, "insresults");//检验结果
                        Float noreceiveqty = MapUtils.getFloat(map1, "noreceiveqty");//不合格数量
                        Float sampquan = MapUtils.getFloat(map1, "sampquan");//抽检数量
                        String prtsummarylineid = MapUtils.getString(map1, "prtsummarylineid");
                        noreceiveqty = qualquantity - receiveqty;
                        handlerService.updateBySql("update gq_puracceptline set noreceiveqty=" + noreceiveqty + " where accertificate ='" + accertificate + "'");
                        if (insresults.equals("合格")) {
                            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prtdetailline where id ='" + prtsummarylineid + "'");
                            if (CollectionUtils.isNotEmpty(bySql2)) {
                                handlerService.updateBySql("update gq_prtdetailline set qualiquan =" + receiveqty + ",insresults='" + insresults + "',sampquan=" + sampquan + " where id='" + prtsummarylineid + "'");
                                List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_prtdetailline where id='" + prtsummarylineid + "'");
                                Map<String, Object> map2 = bySql3.get(0);
                                Float qualiquan = MapUtils.getFloat(map2, "qualiquan");
                                Float sampquan1 = MapUtils.getFloat(map2, "sampquan");
                                float receiveqty1 = qualiquan - sampquan1;

                                handlerService.updateBySql("update gq_prtdetailline set receiveqty=" + receiveqty1 + " where id='" + prtsummarylineid + "'");
                                List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_prtdetailline where id='" + prtsummarylineid + "'");
                                if (CollectionUtils.isNotEmpty(bySql4)) {
                                    Map<String, Object> map3 = bySql4.get(0);
                                    String receiveqty2 = MapUtils.getString(map3, "receiveqty");
                                    BigDecimal bigDecimal = new BigDecimal(receiveqty2);
                                    String unitcost = MapUtils.getString(map3, "unitcost");
                                    BigDecimal bigDecimal1 = new BigDecimal(unitcost);
                                    BigDecimal reamount = new BigDecimal("0");
                                    reamount = bigDecimal.multiply(bigDecimal1);
                                    handlerService.updateBySql("update gq_prtdetailline set reamount=" + reamount + " where id='" + prtsummarylineid + "'");
                                }
                            }
                        } else {
                            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prtdetailline where id ='" + prtsummarylineid + "'");
                            if (CollectionUtils.isNotEmpty(bySql2)) {
                                handlerService.updateBySql("update gq_prtdetailline set insresults='" + insresults + "' where id='" + prtsummarylineid + "'");
                            }
                        }


                    }
                    handlerService.updateBySql("update gq_purchasereceipt set accertificate= 2 where receiptnum='" + receiptnum + "'");
                    String status = "已验收";
                    //查询采购接收生成的采购验收是否都验收成功
                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select id from gq_purchasereceipt where receiptnum='" + receiptnum + "'");
                    if (CollectionUtils.isNotEmpty(bySql2)){
                        int test=0;
                        String prtid = MapUtils.getString(bySql2.get(0), "id");//采购接收id
                        List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + prtid + "'");
                        if (CollectionUtils.isNotEmpty(bySql3)){
                            for (int i=0;i<bySql3.size();i++){
                                Map<String, Object> map1 = bySql3.get(i);
                                String acceptments = MapUtils.getString(map1, "acceptments");//验收要求
                                String insresults = MapUtils.getString(map1, "insresults");//检验结果
                                if (acceptments.contains("04")&& StringUtils.isEmpty(insresults)){
                                    test=test+1;
                                }
                            }
                        }
                        if (test==0){
                            handlerService.updateBySql("update gq_purchasereceipt set status ='" + status + "' where receiptnum='" + receiptnum + "'");
                        }
                    }

                }
            } else {
                handlerService.updateBySql("update gq_puraccept set status='会签中' where id = " + id);
            }

        }
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puraccept where id=" + id);
        Map<String, Object> map = bySql.get(0);
        String status = MapUtils.getString(map, "status");
        String receiptnum = MapUtils.getString(map, "receiptnum");
        if (!status.equals("新建")) {
            handlerService.updateBySql("update gq_purchasereceipt set accertificate= 2 where receiptnum='" + receiptnum + "'");
        } else {
            handlerService.updateBySql("update gq_purchasereceipt set accertificate= 0 where receiptnum='" + receiptnum + "'");
        }
//       else if (flowNode.getId().equals("submit")){
//           boolean flag = op.isFlag();
//           if (flag){
//               List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puraccept where id=" + id);
//               Map<String, Object> map = bySql.get(0);
//               String accertificate = MapUtils.getString(map, "accertificate");
//               String receiptnum = MapUtils.getString(map, "receiptnum");
//               handlerService.updateBySql("update gq_purchasereceipt set accertificate= 2 where receiptnum='"+receiptnum+"'");
//           }
//       }

        super.afterExcuteFlow(app, id, flowNode, op, event);
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        System.out.println("===> enter PuracceptHandler afterSave");
        System.out.println("===> app: " + app);
        System.out.println("===> objName: " + objName);
        System.out.println("===> data: " + data);
        System.out.println("===> isUpdate: " + isUpdate);
        if ("gq_puracceptline".equals(objName)){
            String prtsummarylineid = MapUtils.getString(data, "prtsummarylineid");
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtdetailline where id='" + prtsummarylineid + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                String prtid = MapUtils.getString(bySql1.get(0), "prtid");
                handlerService.updateBySql("update gq_purchasereceipt set accertificate= 2 where id='"+prtid+"'");
            }
        }else if ("gq_puraccept".equals(objName)){
            String id1 = MapUtils.getString(data, "id");
            String accertificate = MapUtils.getString(data, "accertificate");
            List<Map<String, Object>> bySql = handlerService.findBySql("select id from gq_puracceptline where accertificate='" + accertificate + "'");
            if (CollectionUtils.isNotEmpty(bySql)) {
                String id = MapUtils.getString(bySql.get(0), "id");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select testedbyid from gq_testinforma where puracceptlineid='" + id + "'");
                StringBuffer names = new StringBuffer();
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    for (Map<String, Object> stringObjectMap : bySql1) {
                        String testedbyid = MapUtils.getString(stringObjectMap, "testedbyid");
                        testedbyid = getUserName(testedbyid);
                        names.append(",").append(testedbyid);
                    }
                    handlerService.updateBySql("delete from biz_flow_countersign where app='" + app + "' and biz_id = '" + id1 + "'");
                    String sql = "INSERT INTO biz_flow_countersign (app, biz_id, node_id, countersign) VALUES ( '" + app + "', '" + id1 + "', 'approal8', '" + names.toString().replaceFirst(",", "") + "')";
                    handlerService.updateBySql(sql);
                }
            }
        } else if ("gq_testinforma".equals(objName)) {
            String id = MapUtils.getString(data, "id");
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_testinforma where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)) {
                Map<String, Object> map = bySql.get(0);
                String testedbyid = MapUtils.getString(map, "testedbyid");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from sys_user where field10='" + testedbyid + "'");
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    String username = MapUtils.getString(bySql1.get(0), "username");
                    handlerService.updateBySql("update gq_testinforma set username='" + username + "' where id='" + id + "'");
                }
            }

        }

        super.afterSave(app, objName, data, isUpdate);
    }

    public String getUserName(String userid) {
        String username = "";
        List<Map<String, Object>> list = handlerService.findBySql("select username from sys_user where field10='" + userid + "'");
        username = org.apache.commons.collections.MapUtils.getString(list.get(0), "username");
        return username;
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        System.out.println("===> enter PuracceptHandler beforSave");
        System.out.println("===> app: " + app);
        System.out.println("===> objName: " + objName);
        System.out.println("===> data: " + data);
        System.out.println("===> isUpdate: " + isUpdate);
        if ("gq_testinforma".equals(objName)) {
            Float receiveqty = MapUtils.getFloat(data, "receiveqty");
            String testresult = MapUtils.getString(data, "testresult");
            String puracceptlineid = MapUtils.getString(data, "puracceptlineid");
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puracceptline where id='" + puracceptlineid + "'");
            if (CollectionUtils.isNotEmpty(bySql)) {
                Map<String, Object> map = bySql.get(0);
                Float qualquantity = MapUtils.getFloat(map, "qualquantity");
                if (receiveqty.compareTo(qualquantity) != 0 && testresult.equals("合格")) {
                    throw new ServiceException("到货数量与合格数量不一致，请重新查验！");
                }
            }
        }
        super.beforSave(app, objName, data, isUpdate);
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        System.out.println("===> enter PuracceptHandler beforeExcuteFlow");
        System.out.println("===> app: " + app);
        System.out.println("===> id: " + id);
        System.out.println("===> flowNode: " + flowNode);
        System.out.println("===> op: " + op);
        if ("submit".equals(flowNode.getId())) {
            boolean flag = op.isFlag();
            if (flag) {
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puraccept where id=" + id);
                if (CollectionUtils.isNotEmpty(bySql)) {
                    Map<String, Object> map = bySql.get(0);
                    String accertificate = MapUtils.getString(map, "accertificate");
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_puracceptline where accertificate='" + accertificate + "'");
                    if (CollectionUtils.isNotEmpty(bySql1)) {
                        for (int i = 0; i < bySql1.size(); i++) {
                            Map<String, Object> map1 = bySql1.get(i);
                            String id1 = MapUtils.getString(map1, "id");
                            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_testinforma where puracceptlineid='" + id1 + "'");
                            if (CollectionUtils.isEmpty(bySql2)) {
                                return "测试信息为空，不允许提交！";
                            }
                        }
                    }
                }
            }
        }

        // 处理会签逻辑 李大超
        if ("complete".equals(flowNode.getId())) {
            Map<String, Object> data = op.getVariables();
            String accertificate = MapUtils.getString(data, "accertificate");

            // 获取当前用户信息
            LoginAppUser user = SysUserUtil.getLoginAppUser();
            Integer personId = user.getField10();

            // 物料验收行
            List<Map<String, Object>> palList = handlerService.findBySql("select id from gq_puracceptline where accertificate = '" + accertificate + "'");

            if (CollectionUtils.isNotEmpty(palList)) {
                for (Map<String, Object> palMap : palList) {
                    Integer palId = MapUtils.getInteger(palMap, "id");

                    // 更新测试信息
                    handlerService.updateBySql("update gq_testinforma set isapproved = 1 where isapproved = 0 and testedbyid = " + personId + " and puracceptlineid = " + palId);

                    // 查询测试信息
                    List<Map<String, Object>> tiList = handlerService.findBySql("select * from gq_testinforma where isapproved = 1 and puracceptlineid = " + palId);

                    if (CollectionUtils.isNotEmpty(tiList)) {
                        ArrayList<Float> qtyList = new ArrayList<>();
                        List<String> inResultList = new ArrayList<>();
                        List<List> resultList = new ArrayList<>();

                        for (Map<String, Object> tiMap : tiList) {
                            String testedby = MapUtils.getString(tiMap, "testedby");
                            String aptecindica = MapUtils.getString(tiMap, "aptecindica");
                            Float receiveqty = MapUtils.getFloat(tiMap, "receiveqty");
                            String testresult = MapUtils.getString(tiMap, "testresult");

                            qtyList.add(receiveqty);
                            inResultList.add(testresult);

                            List<Object> tempList = new ArrayList<>();
                            tempList.add(testedby);
                            tempList.add(aptecindica);
                            tempList.add(receiveqty);
                            tempList.add(testresult);
                            tempList.add("\n");

                            resultList.add(tempList);
                        }
                        String s = Joiner.on("").join(resultList).replaceAll("]", "")
                                .replaceAll("\\[", "").replaceAll(",", ";");

                        Map<String, Object> updMap = new HashMap<>();
                        updMap.put("id", palId);
                        //修改验收结论
                        updMap.put("acceptansion", s);

                        //修改接收数量
                        Float minQty = Collections.min(qtyList);
                        updMap.put("receiveqty", minQty);

                        // 验收结论
                        String insResult = "";

                        if (inResultList.contains("退货")) {
                            insResult = "退货";
                        } else if (!inResultList.contains("退货") && inResultList.contains("换货")) {
                            insResult = "换货";
                        } else if (!inResultList.contains("退货") && !inResultList.contains("换货") && inResultList.contains("合格")) {
                            insResult = "合格";
                        }
                        updMap.put("insresults", insResult);

                        handlerService.update("gq_puracceptline", updMap);
                    }
                }
            }
        }

        return null;
    }

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        System.out.println("===> enter PuracceptHandler operate");
        System.out.println("===> app: " + app);
        System.out.println("===> type: " + type);
        System.out.println("===> params: " + params);
        if("puracceptApp".equals(app)){
            if ("puraccept".equals(type)){
                //String applyby = MapUtils.getString(params, "applyby");
                String id = MapUtils.getString(params, "id");
                String personid = MapUtils.getString(params, "personid");
                String name = MapUtils.getString(params, "name");
                ArrayList<String> strings = new ArrayList<>();
                strings.add(personid);
                strings.add("personid");
                strings.add(name);
                strings.add("name");
                List<Map<String, Object>> bySql=null;
                if (personid==null&&name==null){
                    bySql = handlerService.findBySql(" select * from gq_person where id not in (select applyby from gq_puracceptline where id='"+id+"') and id not in (select testedbyid from gq_testinforma where puracceptlineid='"+id+"') and nomploysonnel !='否'");
                }else {
                    String list1=" like";
                    String list3="";
                    //String list2="and";
                    for (int i=0;i<strings.size();i=i+2){
                        String s = strings.get(i);
                        if (s!=null){
                            if(list3==""){
                                list3=list3+strings.get(i+1)+list1+"'%"+s+"%'";
                            }else{
                                list3=list3+" and "+strings.get(i+1)+list1+"'%"+s+"%'";
                            }
                        }
                    }
                    bySql = handlerService.findBySql(" select * from gq_person where  "+list3+" and id not in (select applyby from gq_puracceptline where id='"+id+"') and id not in (select testedbyid from gq_testinforma where puracceptlineid='"+id+"') and nomploysonnel !='否'");

                }
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(bySql)) {
                    int page = 1;
                    int limit = 10;
                    if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                        page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                        limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                    }

                    List<Map<String, Object>> collect = bySql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                    return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) bySql.size()).build();
                }
            }
        }
        return super.operate(app, type, params);
    }
}
